# -*- coding = utf-8 -*-
# @Time    : 2025/4/16 下午6:43
# @Author  : yqk
# @File    : 非对称加密.py
# @Software: PyCharm
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

# 生成秘钥对
def generate_key_pair():
    key = RSA.generate(2048)
    private_key = key.export_key()
    public_key = key.publickey().export_key()

    # 保存到文件
    with open('private_key.pem', 'wb') as f:
        f.write(private_key)
    with open('public_key.pem', 'wb') as f:
        f.write(public_key)

    return private_key, public_key

# 加密函数
def encrypt_message(public_key_pem, plain_text):
    public_key = RSA.import_key(public_key_pem)
    cipher = PKCS1_OAEP.new(public_key)
    encrypted = cipher.encrypt(plain_text.encode('utf-8'))
    return encrypted

# 解密函数
def decrypt_message(private_key_pem, encrypted_text):
    private_key = RSA.import_key(private_key_pem)
    cipher = PKCS1_OAEP.new(private_key)
    decrypted = cipher.decrypt(encrypted_text)
    return decrypted.decode('utf-8')

# 测试流程
if __name__ == '__main__':
    # 明文
    plain_text = '这是明文'

    # 生成密钥对
    private_key, public_key = generate_key_pair()

    # 加密
    encrypted_text = encrypt_message(public_key, plain_text)
    print('加密后的数据:', encrypted_text)

    # 解密
    decrypted_text = decrypt_message(private_key, encrypted_text)
    print('解密后的数据:', decrypted_text)
